package service

import (
	"lottery/db"
	"errors"
	"lottery/utils"
	"lottery/exception"
	"lottery/enum"
	"lottery/models"
)


type Bet struct {

}

func (bet *Bet) AddItem(params []*models.Bet) (int64,error) {
	if params==nil ||len(params)==0 {
		return exception.ParamsException,errors.New("required params")
	}
	for _, param := range params {
		if param.UserId==0 {
			return exception.ParamsException,errors.New("required userId")
		}

		if param.Amount<=0 {
			param.Amount=200
			//return exception.ParamsException,errors.New("required amount")
		}

		if param.GameType=="" {
			return exception.ParamsException,errors.New("required gameType")
		}

		if param.Numbers==""{ //numbers
			return exception.ParamsException,errors.New("required numbers")
		}
		if param.Status==""  {
			param.Status=enum.CREATED
		}
	}
	_,err:=db.Master().Insert(params)
	return exception.NoException,err
}


func (bet *Bet) GetItemById(betId int64) ( *models.Bet,error) {
	if betId <= 0 {
		err := errors.New("column Id required")
		return nil,err
	}
	var tmp models.Bet
	_,err:= db.Master().ID(betId).Unscoped().Get(&tmp)

	if err!=nil {
		return nil,err
	}
	//未查询到数据
	if tmp.Id==0 {
		return nil,err
	}
	return &tmp,err
}



func (bet *Bet) GetItemByPage(query *models.Bet,page int,size int) ( []*models.Bet,error) {
	if page <= 0 {
		err := errors.New("page required")
		return nil,err
	}
	var tmp []*models.Bet
	limit,offset:=utils.Page(page,size)

	params:=query
	if params==nil {
		params=&models.Bet{}
	}
	err:= db.Master().Limit(limit,offset).Find(&tmp,params)
	return tmp,err
}


func (bet *Bet) UpdateItemById(betId int64,param *models.Bet) (int64,error) {
	var tmp models.Bet
	_,err:= db.Master().ID(betId).Get(&tmp)
	if err!=nil {
		return exception.ServerException,err
	}
	//未查询到数据
	if tmp.Id==0 {
		return exception.ParamsException,errors.New("Unkown id")
	}

	if param.Status!=""  {
		tmp.Status=param.Status
	}

	rows,err:=db.Master().Id(betId).Update(&tmp)
	if err!=nil {
		return exception.ParamsException,err
	}

	if rows==0 {
		return exception.ParamsException,errors.New("updated 0 rows")
	}
	return exception.NoException,nil
}


func (bet *Bet) DeleteItemById(betId int64) (int64,error) {
	if betId==0 {
		return exception.ParamsException,errors.New("Unkown betId")
	}

	rows, err := db.Master().Id(betId).Delete(&models.Bet{Id:betId})
	if err!=nil {
		return exception.ServerException,err
	}
	if rows==0 {
		return exception.ServerException,errors.New("deleted 0 rows")
	}
	return exception.NoException,nil
}
